package cn.ug.mall.service.impl;

import cn.ug.account.bean.DataDictionaryBean;
import cn.ug.bean.LoginBean;
import cn.ug.bean.base.DataTable;
import cn.ug.bean.base.Page;
import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.config.RedisGlobalLock;
import cn.ug.core.SerializeObjectError;
import cn.ug.core.ensure.Ensure;
import cn.ug.core.login.LoginHelper;
import cn.ug.enums.PayTypeEnum;
import cn.ug.enums.RateKeyEnum;
import cn.ug.feign.DataDictionaryService;
import cn.ug.mall.bean.*;
import cn.ug.mall.mapper.*;
import cn.ug.mall.mapper.entity.*;
import cn.ug.mall.service.GoodsService;
import cn.ug.mall.web.submit.GoodsSearchSubmit;
import cn.ug.mall.web.submit.GoodsSkuSubmit;
import cn.ug.mall.web.submit.GoodsSubmit;
import cn.ug.msg.bean.status.CommonConstants;
import cn.ug.msg.bean.type.SmsType;
import cn.ug.msg.mq.Sms;
import cn.ug.service.impl.BaseServiceImpl;
import cn.ug.util.UF;
import cn.ug.util.UUIDUtils;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.util.StringUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.dozer.DozerBeanMapper;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static cn.ug.config.QueueName.QUEUE_MSG_SMS_SEND;
import static cn.ug.util.ConstantUtil.NORMAL_DATE_FORMAT;

/**
 * @author zhaohg
 * @date 2018/07/06.
 */
@Service
public class GoodsServiceImpl extends BaseServiceImpl implements GoodsService {
    @Resource
    private GoodsMapper           goodsMapper;
    @Resource
    private GoodsSkuMapper        goodsSkuMapper;
    @Resource
    private GoodsImgMapper        goodsImgMapper;
    @Resource
    private OrderItemMapper       orderItemMapper;
    @Resource
    private OrderMapper           orderMapper;
    @Resource
    private BrandMapper           brandMapper;
    @Resource
    private LabelMapper           labelMapper;
    @Resource
    private DozerBeanMapper       dozerBeanMapper;
    @Resource
    private RedisGlobalLock       redisGlobalLock;
    @Resource
    private GoodsAuditMapper      goodsAuditMapper;
    @Resource
    private RateSettingsMapper    rateSettingsMapper;
    @Resource
    private ProcessTemplateMapper processTemplateMapper;
    @Resource
    private CategoryMapper        categoryMapper;
    @Resource
    private AmqpTemplate          amqpTemplate;
    @Resource
    private DataDictionaryService dataDictionaryService;
    @Resource
    private RateSettingsMapper    settingsMapper;

    @Override
    @Transactional
    public SerializeObject insert(GoodsSubmit submit) {

        LoginBean loginBean = LoginHelper.getLoginBean();
        if (loginBean == null || StringUtils.isEmpty(loginBean.getId())) {
            return new SerializeObjectError<>("00000102");
        }

        String labels = StringUtils.join(Arrays.asList(submit.getLabels()), ",");
        GoodsEntity entity = dozerBeanMapper.map(submit, GoodsEntity.class);
        entity.setLabel(labels);
        int processId = submit.getProcessId();
        if (processId > 0) {
            ProcessTemplateEntity process = processTemplateMapper.findById(processId);
            BigDecimal processCost = process.getProcessCost();
            int disCount = process.getDisCount();
            BigDecimal cost = processCost.multiply(new BigDecimal(disCount)).divide(new BigDecimal(100));
            entity.setProcessCost(cost.setScale(4, BigDecimal.ROUND_HALF_UP));
        }
        entity.setOperatorId(loginBean.getId());
        entity.setGoodsCode(UUIDUtils.base58Uuid());
        goodsMapper.insert(entity);

        List<GoodsSkuBean> items = submit.getSkuList();
        Iterator<GoodsSkuBean> iterator = items.iterator();
        String[] imgList = submit.getImgList();
        String[] pictureList = submit.getPictureList();

        insertSkuImg(entity.getId(), iterator, imgList, pictureList);

        return new SerializeObject<>(ResultType.NORMAL, "00000001");
    }

    @Override
    @Transactional
    public SerializeObject update(GoodsSubmit submit) {

        String userId = LoginHelper.getLoginId();
        if (StringUtils.isBlank(userId)) {
            return new SerializeObjectError<>("00000102");
        }
        String labels = StringUtils.join(Arrays.asList(submit.getLabels()), ",");
        GoodsEntity entity = goodsMapper.findById(submit.getId());
        if (entity != null) {
            entity = dozerBeanMapper.map(submit, GoodsEntity.class);
            entity.setLabel(labels);

            int processId = submit.getProcessId();
            if (processId > 0) {
                ProcessTemplateEntity process = processTemplateMapper.findById(processId);
                BigDecimal processCost = process.getProcessCost();
                int disCount = process.getDisCount();
                BigDecimal cost = processCost.multiply(new BigDecimal(disCount)).divide(new BigDecimal(100));
                entity.setProcessCost(cost.setScale(4, BigDecimal.ROUND_HALF_UP));
                entity.setType(process.getType());
            }
            entity.setOperatorId(userId);
            entity.setAuditType(submit.getAuditType()==null?1:submit.getAuditType());
            goodsMapper.update(entity);

            goodsSkuMapper.deleteByGoodsId(submit.getId());
            goodsImgMapper.deleteByGoodsId(submit.getId());

            List<GoodsSkuBean> items = submit.getSkuList();
            Iterator<GoodsSkuBean> iterator = items.iterator();
            String[] imgList = submit.getImgList();
            String[] pictureList = submit.getPictureList();

            insertSkuImg(entity.getId(), iterator, imgList, pictureList);
            return new SerializeObject<>(ResultType.NORMAL, "00000001");
        }
        return new SerializeObjectError( "00000005");
    }

    private void insertSkuImg(long goodsId, Iterator<GoodsSkuBean> iterator, String[] imgList, String[] pictureList) {
        while (iterator.hasNext()) {
            GoodsSkuBean skuBean = iterator.next();
            GoodsSkuEntity skuEntity = dozerBeanMapper.map(skuBean, GoodsSkuEntity.class);
            skuEntity.setGoodsId(goodsId);
            goodsSkuMapper.insert(skuEntity);
        }

        List<String> images = Arrays.asList(imgList);
        Iterator<String> imgIterator = images.iterator();
        while (imgIterator.hasNext()) {
            GoodsImgEntity img = new GoodsImgEntity();
            img.setImgType(GoodsImgEntity.GOODS_DETAIL_LIST_TYPE);
            img.setUrl(imgIterator.next());
            img.setGoodsId(goodsId);
            goodsImgMapper.insert(img);
        }

        List<String> pictures = Arrays.asList(pictureList);
        Iterator<String> picturesIterator = pictures.iterator();
        while (picturesIterator.hasNext()) {
            GoodsImgEntity img = new GoodsImgEntity();
            img.setImgType(GoodsImgEntity.GOODS_BANNER_LIST_TYPE);
            img.setUrl(picturesIterator.next());
            img.setGoodsId(goodsId);
            goodsImgMapper.insert(img);
        }
    }

    @Override
    public SerializeObject findById(Long goodsId) {

        GoodsEntity goodsEntity = goodsMapper.findById(goodsId);
        if (goodsEntity == null) {
            return new SerializeObjectError<>("23000005");
        }
        GoodsBean goodsBean = dozerBeanMapper.map(goodsEntity, GoodsBean.class);

        List<GoodsSkuBean> skuBeans = new ArrayList<>();
        List<GoodsSkuEntity> skuEntityList = goodsSkuMapper.findListByGoodsId(goodsId);
        for (GoodsSkuEntity skuEntity : skuEntityList) {
            GoodsSkuBean skuBean = dozerBeanMapper.map(skuEntity, GoodsSkuBean.class);
            skuBeans.add(skuBean);
        }

        BrandEntity brand = brandMapper.findById(goodsEntity.getBrandId());
        if (brand != null) {
            goodsBean.setBrandName(brand.getName());
        }

        //加工费
        ProcessTemplateEntity process = processTemplateMapper.findById(goodsEntity.getProcessId());
        if (process != null) {
            goodsBean.setProcessName(process.getName());
            goodsBean.setDiscount(process.getDisCount());
            goodsBean.setProcessCost(process.getProcessCost());
        }

        //运费
        RateSettingEntity rate = settingsMapper.findByKeyName(RateKeyEnum.FREIGHT.getKey());
        if (rate != null && StringUtils.isNotBlank(rate.getKeyValue())) {
            JSONObject rateJson = JSONObject.parseObject(rate.getKeyValue());
            goodsBean.setFreight(rateJson.getBigDecimal("fee"));
        }

        CategoryEntity category = categoryMapper.findById(goodsEntity.getCategoryId());
        if (category != null) {
            goodsBean.setCategoryName(category.getName());
        }

        List<String> imgBeans = new ArrayList<>();
        List<String> pictureBeans = new ArrayList<>();
        List<GoodsImgEntity> imgEntityList = goodsImgMapper.findListByGoodsId(goodsId);
        for (GoodsImgEntity imgEntity : imgEntityList) {
            GoodsImgBean imgBean = dozerBeanMapper.map(imgEntity, GoodsImgBean.class);
            if (imgEntity.getImgType() == GoodsImgEntity.GOODS_DETAIL_LIST_TYPE) {
                imgBeans.add(imgBean.getUrl());
            }
            if (imgEntity.getImgType() == GoodsImgEntity.GOODS_BANNER_LIST_TYPE) {
                pictureBeans.add(imgBean.getUrl());
            }
        }
        //标签
        if (StringUtil.isNotEmpty(goodsEntity.getLabel())) {
            List<String> ids = Arrays.asList(goodsEntity.getLabel().split(","));
            goodsBean.setLabels(ids);

            List<LabelEntity> labelEntityList = labelMapper.findListByIds(ids);
            List<LabelBean> labelBeans = new ArrayList<>();
            Iterator<LabelEntity> iterator = labelEntityList.iterator();
            while (iterator.hasNext()) {
                LabelEntity next = iterator.next();
                LabelBean labelBean = dozerBeanMapper.map(next, LabelBean.class);
                labelBeans.add(labelBean);
            }
            goodsBean.setLabelList(labelBeans);
        }

        goodsBean.setSkuList(skuBeans);
        goodsBean.setImgList(imgBeans);
        goodsBean.setPictureList(pictureBeans);

        return new SerializeObject<>(ResultType.NORMAL, "00000001", goodsBean);
    }

    @Override
    public SerializeObject delete(Long goodsId) {
        GoodsEntity entity = goodsMapper.findById(goodsId);
        if (entity != null) {
            goodsMapper.deleteById(goodsId);
            goodsSkuMapper.deleteByGoodsId(goodsId);
        }
        return new SerializeObject<>(ResultType.NORMAL, "00000001");
    }

    @Override
    public SerializeObject updateShelveType(OtherSubmit submit) {
        GoodsEntity entity = goodsMapper.findById(submit.getId());
        if ((entity != null) && (submit.getId().equals(entity.getId()))) {
            if (submit.getType() == 1) {//立即上架
                entity.setIsUp(0);
                entity.setUpTime(null);
                entity.setShelveType(GoodsEntity.SHELVE_UP);
            }
            if (submit.getType() == 2) {//定时上架
                if (StringUtils.isEmpty(submit.getUpTime())) {
                    return new SerializeObjectError("20300213");
                }
                entity.setIsUp(1);
                entity.setUpTime(UF.strToDate(submit.getUpTime(), "yyyy-MM-dd HH:mm"));
            }
            goodsMapper.updateShelveType(entity);
        }
        return new SerializeObject<>(ResultType.NORMAL, "00000001");
    }

    /**
     * 设置商品是否推荐
     *
     * @param submit
     * @return
     */
    @Override
    public SerializeObject updateRecommend(OtherSubmit submit) {
        GoodsEntity entity = goodsMapper.findById(submit.getId());
        if ((entity != null) && (submit.getId().equals(entity.getId()))) {
            GoodsEntity updateEntity = new GoodsEntity();
            updateEntity.setId(submit.getId());
            updateEntity.setIsRecommend(submit.getIsRecommend());
            int rows = goodsMapper.updateShelveType(updateEntity);
            Ensure.that(rows).isLt(1, "00000005");
            return new SerializeObject<>(ResultType.NORMAL, "00000001");
        }
        return new SerializeObject<>(ResultType.ERROR, "00000005");
    }

    @Override
    public SerializeObject updateAuditType(OtherSubmit submit) {
        LoginBean loginBean = LoginHelper.getLoginBean();
        if (loginBean == null) {
            return new SerializeObjectError<>("00000102");
        }

        if (submit.getRemark().length() > 200) {
            return new SerializeObjectError<>("备注不能超200个字符");
        }
        GoodsEntity entity = goodsMapper.findById(submit.getGoodsId());
        if (entity != null) {
            GoodsAuditEntity auditEntity = new GoodsAuditEntity();
            auditEntity.setAuditorId(loginBean.getId());
            auditEntity.setAuditorName(loginBean.getName());
            auditEntity.setRemark(submit.getRemark());
            auditEntity.setGoodsId(submit.getGoodsId());
            auditEntity.setAuditType(submit.getAuditType());//审核状态
            int success = goodsAuditMapper.insert(auditEntity);
            if (success > 0) {
                goodsMapper.updateAuditType(submit);
            }
            return new SerializeObject<>(ResultType.NORMAL, "00000001");
        }
        return new SerializeObjectError("00000005");
    }

    @Override
    public SerializeObject findList(GoodsSearchSubmit submit) {
        QuerySubmit querySubmit = new QuerySubmit();
        submit.setParams(querySubmit);

        int count = goodsMapper.count(querySubmit);
        Page page = new Page(submit.getPageNum(), submit.getPageSize(), count);
        List<GoodsBean> goodsBeans = new ArrayList<>(count);
        if (count > 0) {
            List<GoodsEntity> goodsList = goodsMapper.findList(querySubmit);
            for (GoodsEntity entity : goodsList) {
                goodsBeans.add(dozerBeanMapper.map(entity, GoodsBean.class));
            }
        }
        return new SerializeObject<>(ResultType.NORMAL, "00000001", new DataTable<>(page, goodsBeans));
    }

    @Override
    public SerializeObject findSkuList(Long goodsId) {
        GoodsEntity entity = goodsMapper.findById(goodsId);
        if (entity != null) {

            List<GoodsSkuEntity> list = goodsSkuMapper.findListByGoodsId(goodsId);

            List<GoodsSkuBean> beans = new ArrayList<>();
            Iterator<GoodsSkuEntity> iterator = list.iterator();
            while (iterator.hasNext()) {
                GoodsSkuEntity skuEntity = iterator.next();
                GoodsSkuBean bean = dozerBeanMapper.map(skuEntity, GoodsSkuBean.class);
                beans.add(bean);
            }
            return new SerializeObject<>(ResultType.NORMAL, "00000001", beans);
        }
        return new SerializeObjectError("00000005");
    }

    @Override
    @Transactional
    public SerializeObject updateStock(GoodsSkuSubmit submit) {

        //TODO 要加锁 相关下单减库存
        GoodsEntity entity = goodsMapper.findById(submit.getGoodsId());
        if (entity != null) {
            List<GoodsSkuBean> skuList = submit.getSkuList();
            Map<Long, Integer> map = skuList.stream().collect(Collectors.toMap(GoodsSkuBean::getId, GoodsSkuBean::getStock));
            List<Long> skuIds = skuList.stream().map(GoodsSkuBean::getId).collect(Collectors.toList());
            List<GoodsSkuEntity> list = goodsSkuMapper.findByIds(skuIds);
            Iterator<GoodsSkuEntity> iterator = list.iterator();
            while (iterator.hasNext()) {
                GoodsSkuEntity skuEntity = iterator.next();
                if (map.containsKey(skuEntity.getId()) && map.get(skuEntity.getId()) != null) {
                    skuEntity.setStock(map.get(skuEntity.getId()));
                    this.updateGoodsStock(skuEntity);
                }
            }

            return new SerializeObject<>(ResultType.NORMAL, "00000001");
        }
        return new SerializeObjectError("00000005");
    }

    private void updateGoodsStock(GoodsSkuEntity sku) {
        String key = "updateGoodsStock:" + sku.getGoodsId() + ":" + sku.getId();
        if (redisGlobalLock.lock(key)) {
            try {
                goodsSkuMapper.updateStock(sku);
                int totalStock = goodsSkuMapper.getSumStockByGoodsId(sku.getGoodsId());
                if (totalStock >= 0) {
                    goodsMapper.updateStock(sku.getGoodsId(), totalStock);
                }
            } catch (Exception e) {
                throw e;
            } finally {
                redisGlobalLock.unlock(key);
            }
        }
    }

    @Override
    public SerializeObject auditDetailListByGoodsId(long id) {
        List<GoodsAuditBean> list = new ArrayList<>();
        List<GoodsAuditEntity> goodsAuditEntityList = goodsAuditMapper.findByGoodsIds(id);
        if (CollectionUtils.isNotEmpty(goodsAuditEntityList)) {
            for (GoodsAuditEntity entity : goodsAuditEntityList) {
                GoodsAuditBean bean = dozerBeanMapper.map(entity, GoodsAuditBean.class);
                list.add(bean);
            }
        }

        return new SerializeObject<>(ResultType.NORMAL, "00000001", list);
    }

    @Override
    public SerializeObject downGoods(OtherSubmit submit) {
        GoodsEntity entity = goodsMapper.findById(submit.getId());
        if (entity != null) {
            int success = goodsMapper.downGoodsById(submit);
            if (success > 0) {
                SerializeObject<List<DataDictionaryBean>> beans = dataDictionaryService.findListByClassification(CommonConstants.MsgType.PRODUCT_DOWN_SHELF.getName(), 1);
                if (beans != null && beans.getData() != null) {
                    List<DataDictionaryBean> data = beans.getData();
                    if (data != null && data.size() > 0) {
                        for (DataDictionaryBean bean : data) {
                            Sms sms = new Sms();
                            sms.setPhone(bean.getItemValue());
                            sms.setType(SmsType.GOODS_HAND_UNDER);
                            Map<String, String> paramMap = new HashMap<>(2);
                            paramMap.put("goodName", entity.getName());
                            paramMap.put("reason", submit.getDownRemark());
                            sms.setParamMap(paramMap);
                            amqpTemplate.convertAndSend(QUEUE_MSG_SMS_SEND, sms);
                        }
                    }
                }
            }
            return new SerializeObject<>(ResultType.NORMAL, "00000001");
        }

        return new SerializeObjectError("00000005");
    }

    @Override
    public SerializeObject validateGoods(long skuId, int quantity, String memberId, int type) {
        GoodsSkuEntity skuEntity = goodsSkuMapper.findById(skuId);
        if (skuEntity == null || skuEntity.getGoodsId() == 0) {
            return new SerializeObjectError("20300200");
        }
        GoodsEntity goodsEntity = goodsMapper.findById(skuEntity.getGoodsId());
        if (goodsEntity == null) {
            return new SerializeObjectError("20300200");
        }
        if (goodsEntity.getShelveType() != 2) {
            return new SerializeObjectError("20300215");
        }
        if ((type == PayTypeEnum.GOLD_EXTRACTION.getType() && goodsEntity.getType() == 2) || (type == PayTypeEnum.GOLD_CHANGE.getType() && goodsEntity.getType() == 1)) {
            return new SerializeObjectError("20300204");
        }
        if (skuEntity.getStock() < quantity) {
            if (type == PayTypeEnum.GOLD_CHANGE.getType()) {
                return new SerializeObject<>(ResultType.STOCK_LACKING, "20300205", skuId + ":" + skuEntity.getStock());
            } else if (type == PayTypeEnum.GOLD_EXTRACTION.getType()) {
                return new SerializeObject<>(ResultType.STOCK_LACKING, "20300206", skuId + ":" + skuEntity.getStock());
            } else {
                return new SerializeObject<>(ResultType.STOCK_LACKING, "20300208", skuId + ":" + skuEntity.getStock());
            }
        }
        Calendar calendar = Calendar.getInstance();
        if (goodsEntity.getIsPrompt() == 1 && goodsEntity.getStartPrompt() != null && calendar.getTime().getTime() < goodsEntity.getStartPrompt().getTime()) {
            return new SerializeObjectError("20300202");
        }
        if (goodsEntity.getIsPrompt() == 1 && goodsEntity.getEndPrompt() != null && calendar.getTime().getTime() > goodsEntity.getEndPrompt().getTime()) {
            return new SerializeObjectError("20300202");
        }
        if (goodsEntity.getIsQuota() == 1 && goodsEntity.getQuotaNum() > 0) {
            int num = orderItemMapper.selectNumByMemberId(goodsEntity.getId(), memberId);
            if ((num + quantity) > goodsEntity.getQuotaNum()) {
                return new SerializeObjectError("20300203");
            }
        }
        double payWeight = skuEntity.getGram().doubleValue() * quantity;
        if (goodsEntity.getIsQuota() == 2 && goodsEntity.getQuotaWeight() != null && goodsEntity.getQuotaWeight().doubleValue() > 0) {
            double weight = orderMapper.selectTotalGramByMemberId(goodsEntity.getId(), memberId);
            if ((weight + payWeight) > goodsEntity.getQuotaWeight().doubleValue()) {
                if (type == PayTypeEnum.GOLD_EXTRACTION.getType()) {
                    return new SerializeObjectError("20300206");
                }
                if (type == PayTypeEnum.GOLD_CHANGE.getType()) {
                    return new SerializeObjectError("20300205");
                }
            }
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat(NORMAL_DATE_FORMAT);
        if (type == PayTypeEnum.GOLD_CHANGE.getType()) {
            RateSettingEntity rate = rateSettingsMapper.findByKeyName(RateKeyEnum.IN_GOLD.getKey());
            if (rate != null && StringUtils.isNotBlank(rate.getKeyValue())) {
                JSONObject rateJson = JSONObject.parseObject(rate.getKeyValue());
                double inMaxGram = rateJson.getDouble("inMaxGram");
                double inGram = orderMapper.getSomedayTradeGram(memberId, dateFormat.format(Calendar.getInstance().getTime()), 3);
                if ((inGram + payWeight) > inMaxGram) {
                    return new SerializeObjectError("20300205");
                }
            }
        }
        if (type == PayTypeEnum.GOLD_EXTRACTION.getType()) {
            RateSettingEntity rate = rateSettingsMapper.findByKeyName(RateKeyEnum.TAKE_GOLD.getKey());
            if (rate != null && StringUtils.isNotBlank(rate.getKeyValue())) {
                JSONObject rateJson = JSONObject.parseObject(rate.getKeyValue());
                double takeMaxGram = rateJson.getDouble("takeMaxGram");
                double tokenGram = orderMapper.getSomedayTradeGram(memberId, dateFormat.format(Calendar.getInstance().getTime()), 2);
                if ((tokenGram + payWeight) > takeMaxGram) {
                    return new SerializeObjectError("20300206");
                }
            }
        }
        return new SerializeObject(ResultType.NORMAL, "00000001");
    }

    @Override
    public GoodsSkuBean getGoodsSku(long skuId) {
        if (skuId > 0) {
            GoodsSkuEntity skuEntity = goodsSkuMapper.findById(skuId);
            if (skuEntity != null) {
                GoodsSkuBean entity = dozerBeanMapper.map(skuEntity, GoodsSkuBean.class);
                return entity;
            }
        }
        return null;
    }

    @Override
    public FeeBean getFee(long skuId, int quantity, int type) {
        GoodsSkuEntity skuEntity = goodsSkuMapper.findById(skuId);
        if (skuEntity == null || skuEntity.getGoodsId() == 0) {
            return null;
        }
        GoodsEntity goodsEntity = goodsMapper.findById(skuEntity.getGoodsId());
        if (goodsEntity == null) {
            return null;
        }
        int inIsDiscount = 0;
        int discount = 100;
        if (type == PayTypeEnum.GOLD_CHANGE.getType()) {
            RateSettingEntity changeGoldRate = rateSettingsMapper.findByKeyName(RateKeyEnum.IN_GOLD.getKey());
            if (changeGoldRate != null && StringUtils.isNotBlank(changeGoldRate.getKeyValue())) {
                JSONObject rateJson = JSONObject.parseObject(changeGoldRate.getKeyValue());
                inIsDiscount = rateJson.getIntValue("inIsDiscount");
                discount = rateJson.getIntValue("inDiscount");
            }
        }
        if (type == PayTypeEnum.GOLD_EXTRACTION.getType()) {
            RateSettingEntity extractionGoldRate = rateSettingsMapper.findByKeyName(RateKeyEnum.TAKE_GOLD.getKey());
            if (extractionGoldRate != null && StringUtils.isNotBlank(extractionGoldRate.getKeyValue())) {
                JSONObject rateJson = JSONObject.parseObject(extractionGoldRate.getKeyValue());
                inIsDiscount = rateJson.getIntValue("takeIsDiscount");
                discount = rateJson.getIntValue("takeDiscount");
            }
        }
        FeeBean feeBean = new FeeBean();
        RateSettingEntity rate = rateSettingsMapper.findByKeyName(RateKeyEnum.FREIGHT.getKey());
        if (rate != null && StringUtils.isNotBlank(rate.getKeyValue())) {
            JSONObject rateJson = JSONObject.parseObject(rate.getKeyValue());
            double freight = rateJson.getDouble("fee");
            if (inIsDiscount == 1) {
                feeBean.setFreight(new BigDecimal(freight * discount / 100).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            } else {
                feeBean.setFreight(freight);
            }
        }
        ProcessTemplateEntity processTemplateEntity = processTemplateMapper.findById(goodsEntity.getProcessId());
        if (processTemplateEntity != null) {
            if (inIsDiscount == 1) {
                feeBean.setProcessFee(new BigDecimal(Math.ceil(skuEntity.getGram().doubleValue())).multiply(new BigDecimal(quantity)).multiply(new BigDecimal(processTemplateEntity.getProcessCost().doubleValue() * processTemplateEntity.getDisCount() / 100 * discount / 100)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            } else {
                feeBean.setProcessFee(new BigDecimal(Math.ceil(skuEntity.getGram().doubleValue())).multiply(new BigDecimal(quantity)).multiply(new BigDecimal(processTemplateEntity.getProcessCost().doubleValue() * processTemplateEntity.getDisCount() / 100)).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            }
        }
        feeBean.setGoodsId(goodsEntity.getId());
        feeBean.setName(goodsEntity.getName());
        return feeBean;
    }

    /**
     * 移动端商品详细
     *
     * @param goodsId
     * @return
     */
    @Override
    public SerializeObject getGoodsById(long goodsId) {

        GoodsEntity goodsEntity = goodsMapper.findById(goodsId);
        if (goodsEntity == null || goodsEntity.getShelveType() == GoodsEntity.SHELVE_DOWN) {
            return new SerializeObjectError<>("23000007");
        }

        GoodsBean goodsBean = dozerBeanMapper.map(goodsEntity, GoodsBean.class);
        List<GoodsSkuBean> skuBeans = new ArrayList<>();
        List<GoodsSkuEntity> skuEntityList = goodsSkuMapper.findListByGoodsId(goodsId);
        for (GoodsSkuEntity skuEntity : skuEntityList) {
            GoodsSkuBean skuBean = dozerBeanMapper.map(skuEntity, GoodsSkuBean.class);
            skuBeans.add(skuBean);
        }

        BrandEntity brand = brandMapper.findById(goodsEntity.getBrandId());
        if (brand != null) {
            goodsBean.setBrandName(brand.getName());
        }
        //加工费
        ProcessTemplateEntity process = processTemplateMapper.findById(goodsEntity.getProcessId());
        if (process != null) {
            goodsBean.setProcessName(process.getName());
            goodsBean.setDiscount(process.getDisCount());
            goodsBean.setProcessCost(process.getProcessCost());
        }

        //运费
        RateSettingEntity rate = settingsMapper.findByKeyName(RateKeyEnum.FREIGHT.getKey());
        if (rate != null && StringUtils.isNotBlank(rate.getKeyValue())) {
            JSONObject rateJson = JSONObject.parseObject(rate.getKeyValue());
            goodsBean.setFreight(rateJson.getBigDecimal("fee"));
        }

        if (goodsEntity.getType() == 1) { //提金
            RateSettingEntity takeGoldRate = settingsMapper.findByKeyName(RateKeyEnum.TAKE_GOLD.getKey());
            if (takeGoldRate != null && StringUtils.isNotBlank(takeGoldRate.getKeyValue())) {
                JSONObject rateJson = JSONObject.parseObject(takeGoldRate.getKeyValue());
                goodsBean.setTakeInMaxGram(rateJson.getBigDecimal("takeMaxGram"));
                goodsBean.setTakInDiscount(rateJson.getInteger("takeIsDiscount") > 0 ? rateJson.getInteger("takeDiscount") : 100);
            }
        }

        if (goodsEntity.getType() == 2) { //换金
            RateSettingEntity inGoldRate = settingsMapper.findByKeyName(RateKeyEnum.IN_GOLD.getKey());
            if (inGoldRate != null && StringUtils.isNotBlank(inGoldRate.getKeyValue())) {
                JSONObject rateJson = JSONObject.parseObject(inGoldRate.getKeyValue());
                goodsBean.setTakeInMaxGram(rateJson.getBigDecimal("inMaxGram"));
                goodsBean.setTakInDiscount(rateJson.getInteger("inIsDiscount") > 0 ? rateJson.getInteger("inDiscount") : 100);
            }
        }
        CategoryEntity category = categoryMapper.findById(goodsEntity.getCategoryId());
        if (category != null) {
            goodsBean.setCategoryName(category.getName());
        }

        List<String> imgBeans = new ArrayList<>();
        List<String> pictureBeans = new ArrayList<>();
        List<GoodsImgEntity> imgEntityList = goodsImgMapper.findListByGoodsId(goodsId);
        Iterator<GoodsImgEntity> imgIterator = imgEntityList.iterator();
        while (imgIterator.hasNext()) {
            GoodsImgEntity imgEntity = imgIterator.next();
            GoodsImgBean imgBean = dozerBeanMapper.map(imgEntity, GoodsImgBean.class);
            if (imgEntity.getImgType() == GoodsImgEntity.GOODS_DETAIL_LIST_TYPE) {
                imgBeans.add(imgBean.getUrl());
            }
            if (imgEntity.getImgType() == GoodsImgEntity.GOODS_BANNER_LIST_TYPE) {
                pictureBeans.add(imgBean.getUrl());
            }
        }

        if (StringUtil.isNotEmpty(goodsEntity.getLabel())) {
            List<String> ids = Arrays.asList(goodsEntity.getLabel().split(","));
            goodsBean.setLabels(ids);

            List<LabelEntity> labelEntityList = labelMapper.findListByIds(ids);
            List<LabelBean> labelBeans = new ArrayList<>();
            Iterator<LabelEntity> iterator = labelEntityList.iterator();
            while (iterator.hasNext()) {
                LabelEntity next = iterator.next();
                LabelBean labelBean = dozerBeanMapper.map(next, LabelBean.class);
                labelBeans.add(labelBean);
            }
            goodsBean.setLabelList(labelBeans);
        }

        goodsBean.setSkuList(skuBeans);
        goodsBean.setImgList(imgBeans);
        goodsBean.setPictureList(pictureBeans);
        return new SerializeObject<>(ResultType.NORMAL, "00000001", goodsBean);
    }

    /**
     * 商品列表(move)
     *
     * @return
     */
    @Override
    public SerializeObject getGoodsList(GoodsSearchSubmit submit) {
        QuerySubmit querySubmit = new QuerySubmit();
        submit.setMoveParams(querySubmit);

        int count = goodsMapper.count(querySubmit);
        Page page = new Page(submit.getPageNum(), submit.getPageSize(), count);
        List<GoodsBean> goodsBeans = new ArrayList<>(count);
        if (count > 0) {
            List<GoodsEntity> goodsList = goodsMapper.findList(querySubmit);
            for (GoodsEntity entity : goodsList) {
                GoodsBean goodsBean = dozerBeanMapper.map(entity, GoodsBean.class);
                GoodsSkuEntity goodsSkuEntity = goodsSkuMapper.findMinGoodsId(entity.getId());
                if (goodsSkuEntity!=null){
                    goodsBean.setSellingPrice(goodsSkuEntity.getPrice());
                    goodsBean.setMarketPrice(goodsSkuEntity.getMarketPrice());
                }
                goodsBeans.add(goodsBean);
            }
        }
        return new SerializeObject<>(ResultType.NORMAL, "00000001", new DataTable<>(page, goodsBeans));
    }

    @Override
    public int updateNeedShelvesGoods() {
        return goodsMapper.updateNeedShelvesGoods();
    }

    /**
     * 获取某个类型商品列表（app端）
     *
     * @param submit
     * @return
     */
    @Override
    public SerializeObject getCategoryGoods(GoodsSearchSubmit submit) {
        QuerySubmit querySubmit = new QuerySubmit();
        submit.setMoveParams(querySubmit);
        querySubmit.put("categoryId",submit.getCategoryId());

        int count = goodsMapper.count(querySubmit);
        Page page = new Page(submit.getPageNum(), submit.getPageSize(), count);
        List<GoodsBean> goodsBeans = new ArrayList<>(count);
        if (count > 0) {
            List<GoodsEntity> goodsList = goodsMapper.findList(querySubmit);
            for (GoodsEntity entity : goodsList) {
                GoodsBean goodsBean = dozerBeanMapper.map(entity, GoodsBean.class);
                GoodsSkuEntity goodsSkuEntity = goodsSkuMapper.findMinGoodsId(entity.getId());
                if (goodsSkuEntity!=null){
                    goodsBean.setSellingPrice(goodsSkuEntity.getPrice());
                    goodsBean.setMarketPrice(goodsSkuEntity.getMarketPrice());
                }
                goodsBeans.add(goodsBean);
            }
        }
        return new SerializeObject<>(ResultType.NORMAL, "00000001", new DataTable<>(page, goodsBeans));
    }

    /**
     * 获取推荐商品列表（app端）
     *
     * @param submit
     * @return
     */
    @Override
    public SerializeObject getRecommendGoods(GoodsSearchSubmit submit) {
        QuerySubmit querySubmit = new QuerySubmit();
        submit.setRecommendParams(querySubmit);
        querySubmit.put("categoryId",submit.getCategoryId());
        List<GoodsBean> goodsBeans = new ArrayList<>();
        List<GoodsEntity> goodsList = goodsMapper.findList(querySubmit);
        if (CollectionUtils.isNotEmpty(goodsList)) {
            for (GoodsEntity entity : goodsList) {
                GoodsBean goodsBean = dozerBeanMapper.map(entity, GoodsBean.class);
                GoodsSkuEntity goodsSkuEntity = goodsSkuMapper.findMinGoodsId(entity.getId());
                if (goodsSkuEntity!=null){
                    goodsBean.setSellingPrice(goodsSkuEntity.getPrice());
                    goodsBean.setMarketPrice(goodsSkuEntity.getMarketPrice());
                }
                goodsBeans.add(goodsBean);
            }
        }
        return new SerializeObject<>(ResultType.NORMAL, goodsBeans);
    }

}
